package com.oneday.ashop.console.common.tags;

import com.oneday.ashop.core.entity.Page;
import com.oneday.ashop.core.tags.HTMLTagSupport;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 分页标签
 * User:bob.yang
 * Date 2016/7/13 0013
 */
public class PageTag extends HTMLTagSupport {

    /**
     * 以当前页为中心，显示几个页码的（包括当前页）
     */
    private static final int CENTER_SHOW_NUM = 5;
    private static final int CENTER_SHOW_NUM_MOBILE = 3;
    /**
     * 超链接 - 空
     * 此处从#修改为javascript:void(0)原因：<a href='#'>本身会刷新页面, charisma.js中定义了对<a href='#'>标签阻止刷新;
     *     在社区合作医生的用户列表页面(手机浏览), 不想引入charisma.js、jquery.js等(防止载入过慢)
     *     使用<a href='javascript:void(0)'>标签效果等同
     */
    private static final String HREF_EMPTY = "javascript:void(0)";
    /**
     * 样式 - li禁用
     */
    private static final String CLASS_LI_DISABLED = "disabled";
    /**
     * 文本 - 上一页
     */
    private static final String TEXT_PRE_PAGE = "上一页";
    private static final String TEXT_PRE_PAGE_MOBILE = "<";
    /**
     * 文本 - 下一页
     */
    private static final String TEXT_NEXT_PAGE = "下一页";
    private static final String TEXT_NEXT_PAGE_MOBILE = ">";
    /**
     * 文本 - 省略号样式
     */
    private static final String TEXT_SUSPENSION_POINTS = "......";
    private static final String TEXT_SUSPENSION_POINTS_MOBILE = "...";

    private String href = null;
    private Page page;
    private boolean hasFilter = true;
    /**
     * 用户浏览器User-Agent
     */
    private String userAgent = null;
    private boolean isMobileStyle = false;

    private int centerShowNum = CENTER_SHOW_NUM;
    private String textPrePage = TEXT_PRE_PAGE;
    private String textNextPage = TEXT_NEXT_PAGE;
    private String textSuspensionPoints = TEXT_SUSPENSION_POINTS;

    @Override
    protected String generateHTML() {
        if (page == null) {
            return null;
        }
        if (page.getTotalPages() < 1) {
            return "";
        }
        //选择显示样式
//        selectStyle();
        StringBuilder htmlStr = new StringBuilder();
        if (isMobileStyle){
            htmlStr.append("<div class=\"center\" style=\"padding:0 10px; line-height:30px\"><ul class=\"pagination pagination-centered\">");
        } else {
            htmlStr.append("<div class=\"center\"><ul class=\"pagination pagination-centered\">");
        }
        // 上一页
        if (page.isHasPre()) {
            htmlStr.append(genLinkHtml(genHref(page.getPrePage()), textPrePage));
        } else {
            htmlStr.append(genLinkHtml(HREF_EMPTY, textPrePage, CLASS_LI_DISABLED));
        }
        // 当前页页前面部分
        int _pcS = page.getPageNo() - centerShowNum / 2;
        if (_pcS > 2) {
            htmlStr.append(genLinkHtml(genHref(1), "1")).append("<li><a href=\"" + HREF_EMPTY + "\">" + textSuspensionPoints + "</a></li>");
        } else {
            _pcS = _pcS < 1 ? 1 : _pcS;
            if (_pcS != 1) {
                htmlStr.append(genLinkHtml(genHref(1), "1"));
            }
        }
        // 当前页后面部分
        int _end = (int) Math.min(_pcS + centerShowNum, page.getTotalPages());
        for (; _pcS < _end; _pcS++) {
            if (_pcS == page.getPageNo()) {
                htmlStr.append("<li class=\"active\"><a href=\"" + HREF_EMPTY + "\">").append(_pcS).append("</a></li>");
            } else {
                htmlStr.append(genLinkHtml(genHref(_pcS), String.valueOf(_pcS)));
            }
        }
        if (_pcS < page.getTotalPages()) {
            htmlStr.append("<li><a href=\"" + HREF_EMPTY + "\">" + textSuspensionPoints + "</a></li>").append(genLinkHtml(
                    genHref(page.getTotalPages()), "" + page.getTotalPages()));
        } else {
            if (_pcS == page.getPageNo()) {
                htmlStr.append("<li class=\"active\"><a href=\"" + HREF_EMPTY + "\">").append(_pcS).append("</a></li>");
            } else {
                htmlStr.append(genLinkHtml(genHref(page.getTotalPages()), String.valueOf(page.getTotalPages())));
            }
        }
        // 下一页
        if (page.isHasNext()) {
            htmlStr.append(genLinkHtml(genHref(page.getNextPage()), textNextPage));
        } else {
            htmlStr.append(genLinkHtml(genHref(HREF_EMPTY), textNextPage, CLASS_LI_DISABLED));
        }
        // 拼接右边提示：正常[记录数/总页数]; 手机[无]
        if (isMobileStyle){
            htmlStr.append("</ul></div>");
        } else {
            htmlStr.append("</ul><ul class=\"pagination pull-right\"><li class=\"disabled\"><a>第")
                    .append(page.getIndex() + 1)
                    .append(" - ")
                    .append(page.getIndex() + page.getSize())
                    .append("条记录 / 共")
                    .append(page.getTotal())
                    .append("条</a></li></ul>")
                    .append("</div>");
        }
        return htmlStr.toString();
    }

    /**
     * @param href 超链接地址
     * @param text 文字
     * @return 无样式的超链接HTML
     */
    private String genLinkHtml(String href, String text) {
        return genLinkHtml(href, text, null);
    }

    /**
     * @param pageNo 页数
     * @return 对应页的超链接地址
     */
    private String genHref(long pageNo) {
        StringBuilder link = new StringBuilder();
        link.append(href).append(href.contains("?") ? '&' : '?').append("pageNo=").append(pageNo);
        @SuppressWarnings("unchecked") LinkedHashMap<String, Object> filter = page.getFilter();
        if (hasFilter && filter != null && !filter.isEmpty()) {
            for (Map.Entry<String, Object> entry : filter.entrySet()) {
                String key = entry.getKey();
                Object val = entry.getValue();
                link.append("&filter['").append(key).append("']=").append(val);
            }
        }
        return StringEscapeUtils.escapeHtml4(link.toString());
    }

    /**
     * @param href    超链接地址
     * @param text    文字
     * @param liClass 样式
     * @return 超链接HTML
     */
    private String genLinkHtml(String href, String text, String liClass) {
        StringBuilder linkHtmlStr = new StringBuilder();
        linkHtmlStr.append(" ");
        linkHtmlStr.append("<li");
        if (StringUtils.isNotEmpty(liClass)) {
            linkHtmlStr.append(" class=\"").append(liClass).append('\"');
        }
        linkHtmlStr.append('>');
        linkHtmlStr.append("<a href=\"").append(href).append("\">")
                .append(text).append("</a></li>");
        return linkHtmlStr.toString();
    }

    /**
     * 选择分页样式
     * 当不传入userAgent属性, 或者使用PC浏览器, 使用正常分页样式;
     * 当使用手机浏览器(android\IOS\Weixin), 使用手机分页样式
     */
//    private void selectStyle() {
//        String userAgent = getUserAgent();
//        if (null != userAgent && (CommonUtil.isAndroidUA(userAgent) || CommonUtil.isIOS7_0(userAgent)
//                || CommonUtil.isIOS7_1(userAgent) || CommonUtil.isIphoneUA(userAgent) || CommonUtil.isWeiXin(userAgent))){
//            isMobileStyle = true;
//            centerShowNum = CENTER_SHOW_NUM_MOBILE;
//            textPrePage = TEXT_PRE_PAGE_MOBILE;
//            textNextPage = TEXT_NEXT_PAGE_MOBILE;
//            textSuspensionPoints = TEXT_SUSPENSION_POINTS_MOBILE;
//        }
//    }

    private String genHref(String href) {
        return href;
    }

    public void setPage(Page page) {
        this.page = page;
    }

    public void setHref(String href) {
        this.href = href;
    }

    public void setHasFilter(boolean hasFilter) {
        this.hasFilter = hasFilter;
    }

    public String getUserAgent() {
        return userAgent;
    }

    public void setUserAgent(String userAgent) {
        this.userAgent = userAgent;
    }
}
